# 查找元素封装
import time

from selenium.webdriver.support.wait import WebDriverWait

import config
import utils

log = utils.Logger(config.base_dir + '/log/all.log', level='info')


class Base(object):
    def __init__(self, driver):
        self.driver = driver

    # 查找元素方法封装
    def base_find_element(self, loc, timeout=30, poll=0.5):
        log.logger.info(f"查找的元素为:{loc}")
        return WebDriverWait(self.driver, timeout=timeout, poll_frequency=poll) \
            .until(lambda x: x.find_element(*loc))

    # 点击元素方法封装
    def base_click_element(self, loc):
        log.logger.info(f"查找的元素为:{loc}")
        self.base_find_element(loc).click()

    # 输入元素方法封装
    def base_input_element(self, loc, value):
        log.logger.info(f"查找的元素为:{loc}")
        log.logger.info(f"输入的元素为:{value}")
        el = self.base_find_element(loc)
        el.clear()
        el.send_keys(value)

    # 获取文本信息封装
    def base_get_text(self, loc):
        log.logger.info(f"查找的元素为:{loc}")
        log.logger.info("返回的文本信息为: {}".format(self.base_find_element(loc).text))
        return self.base_find_element(loc).text

    # 截图方法封装
    def base_get_image(self):
        self.driver.get_screenshot_as_file("../image/{}.png".format(time.strftime("%Y_%m_%d %H_%M_%S")))

    # 判断元素是否存在
    def base_element_exist(self, loc):
        try:
            self.base_find_element(loc, timeout=2)
            log.logger.info(f"查找的元素为:{loc}")
            return True
        except:
            log.logger.info("查找的元素不存在当前页面")
            return False

    # 返回首页
    def base_home_page(self, loc):
        self.base_click_element(loc)

    # 切换frame表单
    def base_switch_frame(self, frame_name):
        log.logger.info("frame表单的名称是: {}".format(frame_name))
        self.driver.switch_to.frame(frame_name)

    # 切换回主目录
    def base_frame_content(self):
        self.driver.switch_to.default_content()
